package com.nf.health.app.mine.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.login.activity.LoginActivity;
import com.nf.health.app.db.DbManager;
import com.nf.health.app.models.CheckMessage;
import com.nf.health.app.models.UpdateVo;
import com.nf.health.app.models.Version;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.AppManager;
import com.nf.health.app.utils.AppUtil;
import com.nf.health.app.utils.ContorlViewUtils;
import com.nf.health.app.utils.DataCleanManager;
import com.nf.health.app.utils.DialogHelp;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;

import cn.jpush.android.api.JPushInterface;
import rx.functions.Action1;

/**
 * @author Ian
 * @ClassName: SettingActivity
 * @Description: 设置页面
 * @date 2015-11-4 上午11:03:31
 */
public class SettingActivity extends BaseActivity implements OnClickListener {
    private View rl_modify_account, rl_modify_password, rl_aboutus, rl_modify_infor, ll_advice, ll_update;
    private Button bt_success_submit;

    private ToggleButton sound_tb, shake_tb, yongyao_tb;
    private boolean hasCleared = false;
    private ProgressDialog _waitDialog;

    String sound = "", shake = "", yongyao = "";
    //清除缓存
    private RelativeLayout rl_setting_clear_cache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_setting);

        ViewUtil.setText(this, R.id.titlebar_title_tv, "设置");

		ll_advice = ViewUtil.getView(this, R.id.ll_advice);
        ll_update = ViewUtil.getView(this, R.id.ll_update);
        sound_tb = (ToggleButton) findViewById(R.id.sound_tb);
        shake_tb = (ToggleButton) findViewById(R.id.shake_tb);
        yongyao_tb = (ToggleButton) findViewById(R.id.yongyao_tb);
        rl_modify_account = ViewUtil.getView(this, R.id.rl_modify_account);
        rl_modify_password = ViewUtil.getView(this, R.id.rl_modify_password);
        rl_modify_infor = ViewUtil.getView(this, R.id.rl_modify_infor);
        rl_aboutus = ViewUtil.getView(this, R.id.rl_aboutus);
        rl_setting_clear_cache = ViewUtil.getView(this, R.id.rl_setting_clear_cache);
        bt_success_submit = ViewUtil.getView(this, R.id.bt_success_submit);
        initListener();
        initView();
        registerReceiver();
    }

    private void initListener() {
        rl_modify_password.setOnClickListener(this);
        rl_modify_account.setOnClickListener(this);
        bt_success_submit.setOnClickListener(this);
        rl_aboutus.setOnClickListener(this);
        rl_modify_infor.setOnClickListener(this);
		ll_advice.setOnClickListener(this);
        ll_update.setOnClickListener(this);
        rl_setting_clear_cache.setOnClickListener(this);
        provider.requestCheckMsg("checkmessage");//checkmessage

    }

    private void initView() {

        sound_tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                // TODO Auto-generated method stub
                if (sound.equals("y")) {
                    sound = "n";
                    final AlertDialog dialog;
                    AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
                    LayoutInflater factory = LayoutInflater.from(SettingActivity.this);
                    final View textEntryView = factory.inflate(R.layout.test, null);
                    TextView tixing = (TextView) textEntryView.findViewById(R.id.text_message);
                    ImageView quxiao_image = (ImageView) textEntryView.findViewById(R.id.quxiao_image);
                    Button ok = (Button) textEntryView.findViewById(R.id.ok_btn);
                    Button no = (Button) textEntryView.findViewById(R.id.no_btn);
                    builder.setView(textEntryView);
                    dialog = builder.create();
                    dialog.show();
                    tixing.setText("关闭声音，系统给您推送消息时不会有声音，是否继续关闭");
                    ok.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            provider.requestSettingMsg(sound, shake, yongyao, "SettingMsgSound");
                            dialog.dismiss();
                        }
                    });
                    no.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();
                            provider.requestCheckMsg("checkmessage");//checkmessage
                        }
                    });
                    quxiao_image.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();

                            provider.requestCheckMsg("checkmessage");//checkmessage
                        }
                    });
                } else {
                    sound = "y";
                    provider.requestSettingMsg(sound, shake, yongyao, "SettingMsgSound");
                }
            }
        });
        shake_tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                // TODO Auto-generated method stub

                if (shake.equals("y")) {
                    shake = "n";
                    final AlertDialog dialog;
                    AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
                    LayoutInflater factory = LayoutInflater.from(SettingActivity.this);
                    final View textEntryView = factory.inflate(R.layout.test, null);
                    TextView tixing = (TextView) textEntryView.findViewById(R.id.text_message);
                    ImageView quxiao_image = (ImageView) textEntryView.findViewById(R.id.quxiao_image);
                    Button ok = (Button) textEntryView.findViewById(R.id.ok_btn);
                    Button no = (Button) textEntryView.findViewById(R.id.no_btn);
                    builder.setView(textEntryView);
                    dialog = builder.create();
                    dialog.show();

                    tixing.setText("关闭安全提醒，健康数据异常时将不会得到提示，是否继续关闭");

                    ok.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            shake = "n";
                            provider.requestSettingMsg(sound, shake, yongyao, "SettingMsgSound");
                            dialog.dismiss();
                        }
                    });
                    no.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();

                            provider.requestCheckMsg("checkmessage");//checkmessage
                        }
                    });
                    quxiao_image.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();
                            provider.requestCheckMsg("checkmessage");//checkmessage
                        }
                    });
                } else {
                    shake = "y";
                    provider.requestSettingMsg(sound, shake, yongyao, "SettingMsgSound");
                }
            }
        });
        yongyao_tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                // TODO Auto-generated method stub
                if (yongyao.equals("y")) {
                    yongyao = "n";
                    final AlertDialog dialog;
                    AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
                    LayoutInflater factory = LayoutInflater.from(SettingActivity.this);
                    final View textEntryView = factory.inflate(R.layout.test, null);
                    TextView tixing = (TextView) textEntryView.findViewById(R.id.text_message);
                    ImageView quxiao_image = (ImageView) textEntryView.findViewById(R.id.quxiao_image);
                    Button ok = (Button) textEntryView.findViewById(R.id.ok_btn);
                    Button no = (Button) textEntryView.findViewById(R.id.no_btn);
                    builder.setView(textEntryView);
                    dialog = builder.create();
                    dialog.show();

                    tixing.setText("关闭用药提醒，您的吃药时间将不会得到系统提醒，是否继续关闭");

                    ok.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            provider.requestSettingMsg(sound, shake, yongyao, "SettingMsgSound");
                            dialog.dismiss();
                        }
                    });
                    no.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();
                            provider.requestCheckMsg("checkmessage");//checkmessage
                        }
                    });
                    quxiao_image.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();

                            provider.requestCheckMsg("checkmessage");//checkmessage
                        }
                    });
                } else {
                    yongyao = "y";
                    provider.requestSettingMsg(sound, shake, yongyao, "SettingMsgSound");
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_modify_account:
                ActivityUtils.showActivity(this, ModifyAccountActivity.class);
                break;
            case R.id.rl_modify_infor:
                ActivityUtils.showActivity(this, PersonalInforActivity.class);
                break;
            case R.id.rl_modify_password:
                ActivityUtils.showActivity(this, ModifyPwActivity.class);
                break;
            case R.id.bt_success_submit:
                provider.requestLogout("logout");
                break;
            case R.id.ll_advice:
			ActivityUtils.showActivity(this, FeedbackActivity.class);//反馈
				break;
            case R.id.ll_update:
                provider.CheckVersionNum("CheckVersionNum");
                break;
        /*
         * case R.id.ll_update:
		 * provider.requestCheckVersion("requestCheckVersion"); break;
		 */
            case R.id.rl_aboutus:
                ActivityUtils.showActivity(this, AboutUsActivity.class);
                break;
            case R.id.rl_setting_clear_cache:
                showLoading("清除缓存...");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //获取缓存File
                            File file = SettingActivity.this.getCacheDir();
                            final String size = DataCleanManager.getFileSize(file);
                            DataCleanManager.cleanInternalCache(getApplication());
                            DataCleanManager.cleanExternalCache(getApplication());
                            Thread.sleep(1500);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    hideLoading();
                                    if (!hasCleared) {
                                        hasCleared = true;
                                        showToast("已释放" + size + "空间");
                                    } else {
                                        showToast("已是最佳状态");
                                    }

                                }
                            });
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
        }
        super.onClick(v);
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if ("requestCheckVersion".equals(actionName)) {//不用了
            Version version = (Version) object;
            ContorlViewUtils.checkVersion(version,this);
        } else if ("logout".equals(actionName)) {
            PreferenceHelper.putBoolean(PreferenceHelper.ISLOGIN, false);
//            PreferenceHelper.remove(PreferenceHelper.USERNAME);
//            PreferenceHelper.remove(PreferenceHelper.PASSWORD);
            PreferenceHelper.remove(PreferenceHelper.NF_USER_SESSION);
            PreferenceHelper.remove(PreferenceHelper.USERICON);
            PreferenceHelper.remove(PreferenceHelper.TOKEN);
            PreferenceHelper.remove(PreferenceHelper.USERNICK);
            PreferenceHelper.remove(PreferenceHelper.TYPE_HPID);
            AppManager.getAppManager().finishAllActivity();
            JPushInterface.stopPush(this);
            JPushInterface.clearAllNotifications(this);
            DbManager.getInstance().closeDB();
            EMClient.getInstance().logout(true, new EMCallBack() {

                @Override
                public void onSuccess() {
                    Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
                    ActivityUtils.showActivity(SettingActivity.this, intent);
                }

                @Override
                public void onProgress(int progress, String status) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onError(int code, String message) {
                    // TODO Auto-generated method stub

                }
            });

        } else if (actionName.equals("checkmessage")) {

            CheckMessage checkMessages = (CheckMessage) object;
            //消息

            String soundstr = checkMessages.getSound();
            if (soundstr.equals("y")) {
                sound_tb.setChecked(true);
                sound = "y";
            } else {
                sound_tb.setChecked(false);
                sound = "n";
            }
            //安全提醒
            String safetystr = checkMessages.getSafety();
            if (safetystr.equals("y")) {
                shake_tb.setChecked(true);
                shake = "y";
            } else {
                shake_tb.setChecked(false);
                shake = "n";
            }
            //用药提醒
            String medicstr = checkMessages.getMedic();
            if (medicstr.equals("y")) {
                yongyao_tb.setChecked(true);
                yongyao = "y";
            } else {
                yongyao_tb.setChecked(false);
                yongyao = "n";
            }
        }else if (actionName.equals("SettingMsgSound")) {
            String value = object + "";
            if (value.equals("true")) {
                showToast("设置成功");
            }
        }else if (actionName.equals("CheckVersionNum")) {
            final UpdateVo updateVo = (UpdateVo) object;
            if (Float.valueOf(updateVo.getVersion()) > AppUtil.getVersion(this)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("升级提示");
                builder.setMessage(updateVo.getMsg())
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //下载需要写SD卡权限, targetSdkVersion>=23 需要动态申请权限,华为p9 7.0 emui5.0没有不行
                                RxPermissions.getInstance(SettingActivity.this)
                                        // 申请权限
                                        .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        .subscribe(new Action1<Boolean>() {
                                            @Override
                                            public void call(Boolean granted) {
                                                if (granted) {
                                                    /*long id = AppUtil.downloadApk(SettingActivity.this, updateVo.getDownloadurl());
                                                    PreferenceHelper.putString("download_id", id + "");*/
                                                    ContorlViewUtils.updaAppFromService( updateVo.getDownloadurl(),SettingActivity.this);
                                                } else {
                                                    // 请求失败回收当前服务
                                                    System.out.println("权限失败");
                                                }
                                            }
                                        });
                            }
                        })
                        .setNegativeButton("取消", null).show();
            } else {
                DialogHelp.getMessageDialog(this, "已经是最新版本").setTitle("版本升级").show();
            }
        }
    }

    private CompleteReceiver receiver;

    /**
     * 注册监听APK下载完成的广播
     */
    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        receiver = new CompleteReceiver();
        registerReceiver(receiver, filter);
    }

    private DownloadManager downloadManager;

    class CompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                // TODO 判断这个id与之前的id是否相等，如果相等说明是之前的那个要下载的文件
                int download_id = Integer.parseInt(PreferenceHelper.getString("download_id", ""));
                if (id == download_id) {
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(id);
                    Cursor cursor = downloadManager.query(query);
                    int column = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_FILENAME);
                    if (cursor.moveToNext()) {
                        String path = cursor.getString(column);
                        if (!TextUtils.isEmpty(path)) {
                            AppUtil.installAPK(SettingActivity.this, path);
                        }
                    }
                }

            } else if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
//                showToast("点击通知了");
                //这里取消下载
                downloadManager.remove(Integer.parseInt(PreferenceHelper.getString("download_id", "")));
            }
        }
    }




    @Override
    public void handleActionStart(String actionName, Object object) {
        if ("CheckVersionNum".equals(actionName)) {
            showCheckDialog();
        } else {
            super.handleActionStart(actionName, object);
        }
    }

    @Override
    public void handleActionFinish(String actionName, Object object) {
        if ("CheckVersionNum".equals(actionName)) {
            hideCheckDialog();
        } else {
            super.handleActionFinish(actionName, object);
        }
    }

    private void showCheckDialog() {
        if (_waitDialog == null) {
            _waitDialog = DialogHelp.getWaitDialog(this, "正在获取新版本信息...");
        }
        _waitDialog.show();
    }

    private void hideCheckDialog() {
        if (_waitDialog != null) {
            _waitDialog.dismiss();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        hasCleared = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hasCleared = false;
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

}
